/*
 * @lc app=leetcode.cn id=200 lang=javascript
 *
 * [200] 岛屿数量
 */

// @lc code=start
/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function (grid) {
  let columns = grid[0].length;
  let rows = grid.length;

  const inArea = (row, column) => {
    return row >= 0 && row < rows && column >= 0 && column < columns;
  };

  const dfs = (row, column) => {
    if (
      !inArea(row, column) ||
      grid[row][column] === "0" ||
      grid[row][column] === "2"
    )
      return;
    if (grid[row][column] === "1") grid[row][column] = "2";
    dfs(row - 1, column);
    dfs(row + 1, column);
    dfs(row, column - 1);
    dfs(row, column + 1);
  };

  let cnt = 0;

  for (let i = 0; i < rows; i++)
    for (let j = 0; j < columns; j++) {
      if (grid[i][j] === "1") {
        cnt++;
        dfs(i, j);
      }
    }

  return cnt;
};

// @lc code=end
